package com.ndood.core.social.weixin.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Configuration;
import org.springframework.social.UserIdSource;
import org.springframework.social.connect.ConnectionFactory;
import org.springframework.social.connect.ConnectionFactoryLocator;
import org.springframework.social.connect.UsersConnectionRepository;
import org.springframework.social.security.AuthenticationNameUserIdSource;

import com.ndood.core.properties.SecurityProperties;
import com.ndood.core.properties.WeixinProperties;
import com.ndood.core.social.SocialAutoConfigurerAdapter;
import com.ndood.core.social.SocialConfig;
import com.ndood.core.social.weixin.connect.WeixinConnectionFactory;

/**
 * 微信登录配置
 */
@Configuration  
@ConditionalOnProperty(prefix = "ndood.security.social.weixin", name = "app-id")
public class WeixinAutoConfiguration extends SocialAutoConfigurerAdapter {

	@Autowired
	private SecurityProperties securityProperties;

	@Autowired
	private SocialConfig socialConfig;
	
	@Override
	protected ConnectionFactory<?> createConnectionFactory() {
		WeixinProperties weixinConfig = securityProperties.getSocial().getWeixin();
		return new WeixinConnectionFactory(weixinConfig.getProviderId(), weixinConfig.getAppId(),
				weixinConfig.getAppSecret());
	}
	
	@Override
	public UsersConnectionRepository getUsersConnectionRepository(ConnectionFactoryLocator connectionFactoryLocator) {
		return socialConfig.getUsersConnectionRepository(connectionFactoryLocator);
	}
	
	/**
	 * One configuration class must implement getUserIdSource from SocialConfigurer.
	 * https://www.programcreek.com/java-api-examples/index.php?api=org.springframework.social.UserIdSource
	 */
	@Override
	public UserIdSource getUserIdSource() {
		return new AuthenticationNameUserIdSource();
	}
}